package com.bootdo.system.controller;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.Constant;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.DictService;
import com.bootdo.common.utils.*;
import com.bootdo.system.domain.DeptDO;
import com.bootdo.system.domain.RoleDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.UserNumDo;
import com.bootdo.system.service.RoleService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.vo.UserVO;
import io.swagger.annotations.Api;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/sys/user")
@Api(value="用户管理接口")
@Controller
public class UserController extends BaseController {
	private String prefix="system/user"  ;
	@Autowired
	UserService userService;
	@Autowired
	RoleService roleService;
	@Autowired
	DictService dictService;
	@RequiresPermissions("sys:user:user")
	@GetMapping("")
	String user(Model model) {
		return prefix + "/user";
	}
	
	
	@GetMapping("/yhtx")
	String yhtx(Model model) {
		return prefix + "/yhtx";
	}
	
	@GetMapping("/zjje/{id}")
	String zjje(Model model, @PathVariable("id") Long id) {
		UserDO userDO = userService.get(id);
		model.addAttribute("userName", userDO.getUsername());
		model.addAttribute("userId", userDO.getUserId());
		return prefix + "/zjje";
	}
	
	@GetMapping("/list")
	@ResponseBody
	List<UserDO> list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		UserDO user = ShiroUtils.getUser();
		Long userId = user.getUserId();
		boolean falg=false;
		String deptId1 = (String) params.get("deptId");
		if(("").equals(deptId1)) {
			falg=true;
		}
		List<UserDO> sysUserList=null;
		if(userId != 1 && falg) {
			Long deptId = user.getDeptId();
			params.put("deptId", deptId);
			Query query = new Query(params);
			sysUserList= userService.list(query);
		}else {
			Query query = new Query(params);
			sysUserList= userService.list2(query);
		}
		
		 
//		int total = userService.count(query);
//		PageUtils pageUtil = new PageUtils(sysUserList, total);
		return sysUserList;
	}
	
	
	@GetMapping("/list2")
	@ResponseBody
	List<UserDO> list2(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		UserDO user = ShiroUtils.getUser();
		Long userId = user.getUserId();
		boolean falg=false;
		String deptId1 = (String) params.get("deptId");
		if(("").equals(deptId1)) {
			falg=true;
		}
		List<UserDO> sysUserList=null;
		if(userId != 1) {
			Long deptId = user.getDeptId();
			params.put("deptId", deptId);
			Query query = new Query(params);
			sysUserList= userService.list(query);
		}else {
			Query query = new Query(params);
			sysUserList= userService.list2(query);
		}
		
		 
//		int total = userService.count(query);
//		PageUtils pageUtil = new PageUtils(sysUserList, total);
		return sysUserList;
	}

	@RequiresPermissions("sys:user:add")
	@Log("添加用户")
	@GetMapping("/add")
	String add(Model model) {
		List<RoleDO> roles = roleService.list();
		Long userId = getUserId();
		if(userId != 1) {
			for (int i = 0; i < 2; i++) {
				roles.remove(roles.size()-1);
			}
		}
		model.addAttribute("roles", roles);
		return prefix + "/add";
	}
	
	@RequiresPermissions("sys:user:addAll")
	@Log("批量添加用户")
	@GetMapping("/addAll")
	String addAll(Model model) {
		List<RoleDO> roles = roleService.list();
		model.addAttribute("roles", roles);
		return prefix + "/addAll";
	}

	@RequiresPermissions("sys:user:edit")
	@Log("编辑用户")
	@GetMapping("/edit/{id}")
	String edit(Model model, @PathVariable("id") Long id) {
		UserDO userDO = userService.get(id);
		model.addAttribute("user", userDO);
		List<RoleDO> roles = roleService.list(id);
		model.addAttribute("roles", roles);
		return prefix+"/edit";
	}

	
	
	
	
	@RequiresPermissions("sys:user:add")
	@Log("保存用户")
	@PostMapping("/save")
	@ResponseBody
	R save(UserDO user) {
		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		user.setPassword(MD5Utils.encrypt(user.getUsername(), user.getPassword()));
		if (userService.save(user) > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	@SuppressWarnings("static-access")
	@RequiresPermissions("sys:user:add")
	@Log("批量生成用户")
	@PostMapping("/saveNum")
	@ResponseBody
	R saveNum(UserNumDo  userNumDo) {
		int flag=0;
		if(userNumDo != null) {
			int num = userNumDo.getUserNum();
			if(num > 0) {
				String password="000000";
				if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
					return R.error(1, "系统不允许修改");
				}
				int timestamp = this.getSecondTimestamp(new Date());
				for (int i = 0; i < num; i++) {
					UserDO userDO = new UserDO();
					String userName=userNumDo.getUserPrefix()+(timestamp+i);
					userDO.setUsername(userName);
					userDO.setPassword(MD5Utils.encrypt(userName,password));
					userDO.setName(userName);
					userDO.setStatus(1);
					userDO.setRoleIds(userNumDo.getRoleIds());
					userDO.setDeptId(userNumDo.getDeptId());
					flag = userService.save(userDO);
				}
			}
		}
		if(flag > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:edit")
	@Log("更新用户")
	@PostMapping("/update")
	@ResponseBody
	R update(UserDO user) {
		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		if (userService.update(user) > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	@PostMapping("/update2")
	@ResponseBody
	R update2(UserDO user) {
		UserDO userByUserName = userService.getUserByUserName(user.getUsername());
		if(userByUserName == null) {
			if (userService.update2(user) > 0) {
				return R.ok();
			}
		}else {
			return R.error("用户名已经存在");
		}
		return R.error();
	}


	@Log("更新用户")
	@PostMapping("/updatePeronal")
	@ResponseBody
	R updatePeronal(UserDO user) {
		if (userService.updatePersonal(user) > 0) {
			return R.ok();
		}
		return R.error(500,"该用户名已存在");
	}
	
	@Log("更新用户")
	@PostMapping("/updateZfb")
	@ResponseBody
	R updateZfb(UserDO user) {
		if (userService.updateZfb(user) > 0) {
			return R.ok();
		}
		return R.error(500,"该用户名已存在");
	}


	@RequiresPermissions("sys:user:remove")
	@Log("删除用户")
	@PostMapping("/remove")
	@ResponseBody
	R remove(Long id) {
		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		if (userService.remove(id) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@RequiresPermissions("sys:user:batchRemove")
	@Log("批量删除用户")
	@PostMapping("/batchRemove")
	@ResponseBody
	R batchRemove(@RequestParam("ids[]") Long[] userIds) {
		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		int r = userService.batchremove(userIds);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}

	@PostMapping("/exit")
	@ResponseBody
	boolean exit(@RequestParam Map<String, Object> params) {
		// 存在，不通过，false
		return !userService.exit(params);
	}

	@RequiresPermissions("sys:user:resetPwd")
	@Log("请求更改用户密码")
	@GetMapping("/resetPwd/{id}")
	String resetPwd(@PathVariable("id") Long userId, Model model) {

		UserDO userDO = new UserDO();
		userDO.setUserId(userId);
		model.addAttribute("user", userDO);
		return prefix + "/reset_pwd";
	}

	@Log("提交更改用户密码")
	@PostMapping("/resetPwd")
	@ResponseBody
	R resetPwd(UserVO userVO) {
		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		try{
			userService.resetPwd(userVO,getUser());
			return R.ok();
		}catch (Exception e){
			return R.error(1,e.getMessage());
		}

	}
	@RequiresPermissions("sys:user:resetPwd")
	@Log("admin提交更改用户密码")
	@PostMapping("/adminResetPwd")
	@ResponseBody
	R adminResetPwd(UserVO userVO) {
		if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		try{
			userService.adminResetPwd(userVO);
			return R.ok();
		}catch (Exception e){
			return R.error(1,e.getMessage());
		}

	}
	@GetMapping("/tree")
	@ResponseBody
	public Tree<DeptDO> tree() {
		Tree<DeptDO> tree = new Tree<DeptDO>();
		tree = userService.getTree();
		return tree;
	}

	@GetMapping("/treeView")
	String treeView() {
		return  prefix + "/userTree";
	}
	
	
	@GetMapping("/personal")
	String personal(Model model) {
		UserDO userDO  = userService.get(getUserId());
		model.addAttribute("user",userDO);
		model.addAttribute("hobbyList",dictService.getHobbyList(userDO));
		model.addAttribute("sexList",dictService.getSexList());
		return prefix + "/personal";
	}
	@ResponseBody
	@PostMapping("/uploadImg")
	R uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request) {
		if ("test".equals(getUsername())) {
			return R.error(1, "演示系统不允许修改,完整体验请部署程序");
		}
		Map<String, Object> result = new HashMap<>();
		try {
			result = userService.updatePersonalImg(file, avatar_data, getUserId());
		} catch (Exception e) {
			return R.error("更新图像失败！");
		}
		if(result!=null && result.size()>0){
			return R.ok(result);
		}else {
			return R.error("更新图像失败！");
		}
	}
	
    /** 
     * 获取精确到秒的时间戳 
     * @return 
     */  
    public static int getSecondTimestamp(Date date){  
        if (null == date) {  
            return 0;  
        }  
        String timestamp = String.valueOf(date.getTime());  
        int length = timestamp.length();  
        if (length > 3) {  
            return Integer.valueOf(timestamp.substring(0,length-3));  
        } else {  
            return 0;  
        }  
    }  
    
    
    @PostMapping("/saveZjje")
	@ResponseBody
	R saveZjje(Long czrid,String money) {
    	UserDO userDO = userService.get(czrid);
    	String balance = userDO.getBalance();
    	Double double2String = getDouble2String(balance);
    	Double double2String2 = getDouble2String(money);
    	Double res=double2String+double2String2;
    	userDO.setBalance(res+"");
    	int update4 = userService.update4(userDO);
    	if(update4 > 0) {
    		return R.ok();
    	}
		return R.error();
	}
    
    private Double getDouble2String(String num) {
		if(StringUtils.isNoneBlank(num)) {
			Double cny = Double.parseDouble(num);
			DecimalFormat df = new DecimalFormat("0.00000"); 
			String CNY = df.format(cny);
			Double cny1 = Double.parseDouble(CNY);
			return cny1;
		}
		return 0.00;
	}
}
